import os, sys, re, time, gzip
import simplejson as json
import urllib, urllib2, httplib
from BeautifulSoup import BeautifulSoup
from urlparse import urlparse, urlsplit
import StringIO
import mimetypes, mimetools
from ConfigParser import ConfigParser


class Job(object):
    _supported_attribs = ['JobTitle', 'CompanyName', 'JobDescription', 'Locations', 'Experience', 'KeySkills', 'Function', 'Role', 'PostedOn', 'ContactDetails', 'JobUrl' ]
    _supported_formats = [ 'csv', 'xml', 'object' ]
    def __init__(self, attribs={}):
	self.__dict__['jobtitle'] = ""
	self.__dict__['companyname'] = ""
	self.__dict__['jobdescription'] = ""
	self.__dict__['location'] = ""
	# Key 'locations' is being added to temporarily handle a bug in timesjobs.py.
	self.__dict__['locations'] = ""
	self.__dict__['experience'] = ""
	self.__dict__['keyskills'] = ""
	self.__dict__['function'] = ""
	self.__dict__['role'] = ""
	self.__dict__['postedon'] = ""
	self.__dict__['contactdetails'] = ""
	self.__dict__['joburl'] = ""
	for attrIndex in range(0, (self.__class__._supported_attribs.__len__())):
	    if attribs.has_key(self.__class__._supported_attribs[attrIndex]):
		if attrIndex == 0:
		    self.__dict__['jobtitle'] = attribs[self.__class__._supported_attribs[attrIndex]]
		elif attrIndex == 1:
		    self.__dict__['companyname'] = attribs[self.__class__._supported_attribs[attrIndex]]
		elif attrIndex == 2:
		    self.__dict__['jobdescription'] = attribs[self.__class__._supported_attribs[attrIndex]]
		elif attrIndex == 3:
		    self.__dict__['locations'] = attribs[self.__class__._supported_attribs[attrIndex]]
		elif attrIndex == 4:
		    self.__dict__['experience'] = attribs[self.__class__._supported_attribs[attrIndex]]
		elif attrIndex == 5:
		    self.__dict__['keyskills'] = attribs[self.__class__._supported_attribs[attrIndex]]
		elif attrIndex == 6:
		    self.__dict__['function'] = attribs[self.__class__._supported_attribs[attrIndex]]
		elif attrIndex == 7:
		    self.__dict__['role'] = attribs[self.__class__._supported_attribs[attrIndex]]
		elif attrIndex == 8:
		    self.__dict__['postedon'] = attribs[self.__class__._supported_attribs[attrIndex]]
	    	elif attrIndex == 9:
		    self.__dict__['contactdetails'] = attribs[self.__class__._supported_attribs[attrIndex]]
		elif attrIndex == 10:
		    self.__dict__['joburl'] = attribs[self.__class__._supported_attribs[attrIndex]]

    def dumpData(self, filehndl, format="csv"):
	retval = 0
	if format.lower() == "csv":
	    retval = self._dumpCsv(filehndl)
	elif format.lower() == "xml":
	    retval = self._dumpXml(filehndl)
	elif format.lower() == "object":
	    retval = self._dumpObject(filehndl)
	else:
	    print "Unsupported format %s. Supported formats are: %s\n"%(format, ", ".join(self.__class__._supported_formats))
	return(retval)

    def _dumpCsvHeader(cls, filehndl):
	if (filehndl.mode != 'w' and filehndl.mode != 'wb') or filehndl.closed == True:
	    print "_dumpCsv: filehandle is unusable.\n"
	    return None
	headerline = ""
	for attrib in cls._supported_attribs:
	    headerline += attrib + ","
	headerline = headerline[:-1] + "\n"
	filehndl.write(headerline)
	return(headerline)
    _dumpCsvHeader = classmethod(_dumpCsvHeader)

    def _dumpXmlHeader(cls, filehndl):
	if (filehndl.mode != 'w' and filehndl.mode != 'wb') or filehndl.closed == True:
	    print "_dumpCsv: filehandle is unusable.\n"
	    return None
	headerline = ""
	# Code for writing the header as XML goes here...
    _dumpXmlHeader = classmethod(_dumpXmlHeader)

    def _dumpObjectHeader(cls, filehndl):
	if (filehndl.mode != 'w' and filehndl.mode != 'wb') or filehndl.closed == True:
	    print "_dumpCsv: filehandle is unusable.\n"
	    return None
	headerline = ""
	# Code for writing the header as object format goes here...
    _dumpObjectHeader = classmethod(_dumpObjectHeader)

    def dumpHeader(cls, filehndl, format="csv"):
	retval = 0
	if format.lower() == "csv":
	    retval = cls._dumpCsvHeader(filehndl)
	elif format.lower() == "xml":
	    retval = cls._dumpXmlHeader(filehndl)
	elif format.lower() == "object":
	    retval = cls._dumpObjectHeader(filehndl)
	else:
	    print "Unsupported format %s. Supported formats are: %s\n"%(format, ", ".join(cls._supported_formats))
	return(retval)
    dumpHeader = classmethod(dumpHeader)

    def _dumpCsv(self, filehandle):
	if (filehandle.mode != 'w' and filehandle.mode != 'wb') or filehandle.closed == True:
	    print "_dumpCsv: filehandle is unusable.\n"
	    return None
	else:
	    line = ""
	    for attrib in self.__class__.supportedAttributes():
		line += "\"" + self.__dict__[attrib.lower()] + "\","
	    line = line[0:-1]
	    uline = line.encode('utf-8') # handle unicode
	    filehandle.write(uline + "\n")
	return (uline + "\n")

    def _dumpXml(self, filehandle):
	if (filehandle.mode != 'w' and filehandle.mode != 'wb') or filehandle.closed == True:
	    print "_dumpXml: filehandle is unusable.\n"
	    return None
	else:
	    pass # Handle the data here


    def _dumpObject(self, filehandle):
	if (filehandle.mode != 'w' and filehandle.mode != 'wb') or filehandle.closed == True:
	    print "_dumpObject: filehandle is unusable.\n"
	    return None
	else:
	    pass # Handle the data here

    def supportedAttributes(cls):
	return (cls._supported_attribs)
    supportedAttributes = classmethod(supportedAttributes)

    # Define getter/setter methods for all attributes.
    def __getattr__(self, attrib_name):
	for attrib in self.__class__._supported_attribs:
	    if attrib.lower() == attrib_name.lower():
		return (self.__dict__[attrib_name.lower()])
	raise AttributeError

    def __setattr__(self, attrib_name, attrib_val=None):
	for attrib in self.__class__._supported_attribs:
	    if attrib.lower() == attrib_name.lower():
		prev_attrib_val = self.__dict__[attrib_name.lower()]
		self.__dict__[attrib_name.lower()] = attrib_val
		return(prev_attrib_val)
	raise AttributeError



def test_main():
    test_job = {'JobTitle' : r"Openings for secretary (Female only) in Chennai", 'CompanyName' : r"Pay 4 Pay Business Services", 'JobDescription' : r"", 'Locations' : "Vijayawada, Visakhapatnam", 'Experience' : "0 - 2 years", 'KeySkills' : "female", 'Function' : "Admin/Secretarial", 'Role' : "&bull; Fresher<br /> &bull; Typist<br /> &bull; Receptionist/ Front Desk<br /> &bull; Secretarial", 'PostedOn' : "28th Apr 2012", 'ContactDetails' : "", 'JobUrl' : "http://jobs.monsterindia.com/details/11364020.html?sig=js-1-66339317b823ea877cae76ee23160c78-1&from=" }
    job = Job(test_job)
    print "Job Title: " + job.JobTitle
    print "Company Name: " + job.COMPANYNAME
    job.jobtitle = "New Job"
    print "Job Title: " + job.JobTitle
    fh = open("testdumps/tmp.csv", "w")
    job.dumpData(fh)
    fh.close()
    return(1)


if __name__ == "__main__":
    test_main()




